//
//  ButtonGroup.swift
//  SimpleCal
//
//  Created by 杜晓祥 on 2021/12/7.
//

import Cocoa

class ButtonGroup<T: BaseViewButton> {
    
    private var changeValue = ChangeValue()
    
    var check:Bool = false
    
    var btnChange: ((_ params: T)->())?
    
    init() {
    }
    
    init(check: Bool) {
        self.check = check
    }
    
    /**
     新增按钮到按钮组
     --parameters: button
     */
    func addSubview(button: T) {
        button.onClick = buttonClick
        changeValue.allButton.append(button)
    }
    
    func getSubview(index:Int) -> T {
        return changeValue.allButton[index]
    }
    
    func findAll() -> [T] {
        return changeValue.allButton
    }
    
    func count() -> Int {
        return changeValue.allButton.count
    }
    
    func getSelected() -> T? {
        return changeValue.selectValue
    }
    
    private func buttonClick(_ sender: BaseViewButton, _ event: NSEvent) {
        let b = sender as! T
        changeValue.selectValue = b
        if check {
            btnChange?(b)
            return
        }
        let s = b.state
        clean()
        b.state = s
        btnChange?(b)
    }
    
    /**
     清除所有选中项，改为初始状态:.off
     */
    func clean () {
        for t in changeValue.allButton {
            t.state = .off
        }
    }
    
    /**
     设置按钮组启用禁用
     */
    var isEnable: Bool = true {
        didSet {
            for t in changeValue.allButton {
                t.isEnable = isEnable
            }
        }
    }
    
    struct ChangeValue {
        var selectValue: T?
        var buttonMap = [Int: [T]]()
        var state: Int = 2
        var allButton = [T]()
    }
}
